import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:one_context/one_context.dart';
import 'package:rxdart/rxdart.dart';

import 'hc_gesture_detector.dart';
import 'hc_gesture_detector.dart';
import 'hc_painter.dart';
import 'package:uuid/uuid.dart';

var uuid = Uuid();

Future<void> setEnabledSystemUIOverlays(List<String> overlays) async {
  await SystemChannels.platform
      .invokeMethod<void>('SystemChrome.setEnabledSystemUIOverlays', overlays);
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  setEnabledSystemUIOverlays([]);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  static final GlobalKey OneContextKey =
      GlobalKey(debugLabel: '__OneContextKey__');
  static final GlobalKey EasyLoadingKey =
      GlobalKey(debugLabel: '__EasyLoadingKey__');

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          // This is the theme of your application.
          //
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          primarySwatch: Colors.blue,
        ),
        home: HcCanvasGesture(),
        builder: (context, child) {
          return OneContext().builder(
              context, FlutterEasyLoading(child: child, key: EasyLoadingKey),
              key: OneContextKey);
        });
  }
}

class HcCanvasGesture extends StatefulWidget {
  @override
  _HcCanvasGestureState createState() => _HcCanvasGestureState();
}

class _HcCanvasGestureState extends State<HcCanvasGesture> {
  final Size containerSize = new Size(500, 450);
  final Model model = Model.createDefault();
  ui.Image _assetImageFrame; //本地图片
  List<Offset> points = <Offset>[];

  void _initPoints() {
    List<Offset> _points = <Offset>[];
    for (double i = 0; i < 10000; i++) {
      _points.add(Offset(i * 5, i * 5));
    }
    Stream.fromIterable(_points)
        .interval(Duration(seconds: 1))
        .timeInterval()
        .listen((data) {
      model.updateDynamicNode(data.value);
    });
  }

  @override
  void initState() {
    super.initState();
    _getAssetImage();
    //_initPoints();
    //EasyLoading.show(status: 'loading...');
//    OneContext().popDialog(1);
//     new Timer(new Duration(seconds: 5), () => {model.setAgv(Offset(500, 300))});
  }

  @override
  void reassemble() {
    // model.moveTo(Offset(500, 300));
  }

  _getAssetImage() async {
    ui.Image imageFrame = await getAssetImage('assets/images/bmap.png');
    setState(() {
      _assetImageFrame = imageFrame;
    });
  }

  /// 通过assets路径，获取资源图片
  Future<ui.Image> getAssetImage(String asset, {width, height}) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  xhc() {
    final t = new DateTime.now().millisecondsSinceEpoch;
    final r = randNum(min: 10, max: 99);
    for (int i = 0; i < 1000; i++) {
      print(randNum(min: 10, max: 99));
    }
    final ud = uuid.v4().replaceAll(new RegExp('-'), '');
    print("$r$t$ud");
  }

  int randNum({int min = 0, int max = 0}) {
    return (Random().nextDouble() * (max - min + 1) + min).floor();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey, width: 0.5),
              ),
              width: 500,
              height: 450,
              child: ClipRect(
                child: HcGestureDetector(
                  child: LayoutBuilder(builder: (context, constraints) {
                    if (_assetImageFrame != null) {
                      model.setSize(
                          Size(constraints.maxWidth, constraints.maxHeight),
                          Size(_assetImageFrame.width.toDouble(),
                              _assetImageFrame.height.toDouble()));
                    }

                    return CustomPaint(
                      foregroundPainter: HcPainter(model, _assetImageFrame),
                      isComplex: true,
                      child: Container(
                        width: constraints.maxWidth,
                        height: constraints.maxHeight,
                        color: Colors.grey.shade300,
                      ),
                    );
                  }),
                  onScaleStart: (initialFocusPoint) =>
                      model.startScaleRotate(initialFocusPoint),
                  onScaleUpdate: (event) =>
                      model.updateScaleRotate(event.scale, event.focalPoint, 0),
                  onScaleEnd: () => model.staging(),
                  onMoveUpdate: model.moving,
                  bypassTapEventOnDoubleTap: true,
                  bypassMoveEventAfterLongPress: false,
                  onMoveStart: (event) => model.startMoving(event.position),
                  onMoveEnd: (_) => model.endMoving(),
                ),
              )),
          Text('你好啊'),
          FlatButton(
            onPressed: () => {
              // xhc()
              model.changeEdit()
            },
            child: Text('Edit'),
            textColor: Colors.red,
          ),
          FlatButton(
            onPressed: () => {model.setPoint()},
            child: Text('point'),
            textColor: Colors.blue,
          )
        ],
      ),
    );
  }
}
